package com.education.seckill.controller;


import com.education.seckill.entity.SeckillGood;
import com.education.seckill.entity.SeckillOrder;
import com.education.seckill.service.ISeckillGoodService;
import com.education.seckill.utils.R;
import com.education.seckill.vo.SeckillTime;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mr.Tang
 * @since 2022-06-20
 */
@RestController
@CrossOrigin
@RequestMapping("/seckillGood")
public class SeckillGoodController implements InitializingBean {

    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private RedisTemplate redisTemplate;




    @GetMapping("getAll")
    public R getAllSeckillGood(){
            return R.ok().data("goodList",seckillGoodService.list());
    }


    @GetMapping("getById/{id}")
    public R getBookById(@PathVariable("id")String id){
        Object goodObj = redisTemplate.opsForValue().get("secgood" + id);
        ObjectMapper objectMapper = new ObjectMapper();
        SeckillGood good = objectMapper.convertValue(goodObj, SeckillGood.class);
        long timeDifferent=  seckillGoodService.getCountTimeDifferent(id);
        return R.ok().data("timeDifferent",timeDifferent).data("good",good);
    }


    @GetMapping("updateById/{id}")
    public R updateById(@PathVariable("id")String id){
         seckillGoodService.updateGoodStatus(id);
        return R.ok();
    }


    //系统初始化之前,把秒杀商品信息放入到redis当中
    @Override
    public void afterPropertiesSet() throws Exception {
        List<SeckillGood> list = seckillGoodService.list();
        for (SeckillGood s : list) {
            redisTemplate.opsForValue().set("secgood"+s.getSGoodId(),s);
            redisTemplate.opsForValue().set("secgoodCount"+s.getSGoodId(),s.getSGoodStock());
        }
    }
}
